<?php
/**
 * Desc: Service模板
 * User: zdb
 * Date: 2023/6/5
 * Time: 11:22
 */

namespace app\api\service\project;
use think\facade\Db;

class ProjectModuleTrunkService
{

    private $primaryTable;

    public function __construct()
    {
        $this->primaryTable = "yj_project_module_trunk";
    }

    public function findRowById($id)
    {
        return Db::table($this->primaryTable)->alias('a')
            ->where('id', '=', $id)
            ->strict(false)
            ->find();
    }

    public function findRowByData($data)
    {
        $condition = $this->assembleFilterCondition($data);
        return Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->strict(false)
            ->find();
    }

    public function getListByManyId($arrId)
    {
        $list = Db::table($this->primaryTable)->alias('a')
            ->whereIn('id', $arrId)
            ->select()
            ->toArray();
        return $list;
    }

    public function assembleFilterCondition($data)
    {
        $condition = ['a.status = 1'];

        if (!empty($data['title'])) {
            $condition[] = "title like '%" . $data['title'] . "%'";
        }

        if (!empty($data['project_basic_id'])) {
            $condition[] = "project_basic_id =".$data['project_basic_id'];
        }

        if (!empty($data['module_trunk_name'])) {
            $condition[] = "module_trunk_name like '%" . $data['module_trunk_name'] . "%'";
        }

        return empty($condition) ? "" : implode(" AND ", $condition);
    }

    public function getListNoPage($data = [], $limitNum = 30)
    {
        $condition = $this->assembleFilterCondition($data);
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->limit(0, $limitNum)
            ->order('a.sort asc,a.id desc')
            ->select()
            ->toArray();
        return $res;
    }

    public function getListWithPage($data, $pageIndex = 1, $pageSize = 30)
    {
        $offset = ($pageIndex - 1) * $pageSize;
        $condition = $this->assembleFilterCondition($data);
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->limit($offset, $pageSize)
            ->order('a.id desc')
            ->select();
        return $res;
    }

    public function getTotalNum($data)
    {
        $condition = $this->assembleFilterCondition($data);
        $num = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->count();
        return $num;
    }

    public function createRow($data)
    {
        $data['status'] = isset($data['status']) ? $data['status']:1;
        $res = Db::table($this->primaryTable)
            ->strict(false)
            ->insert($data, true);
        return $res;
    }

    public function createManyRow($data)
    {
        $res = Db::table($this->primaryTable)
            ->strict(false)
            ->duplicate($data)
            ->insertAll($data, true);
        return $res;
    }

    public function updateRowById($id, $data)
    {
        $res = Db::table($this->primaryTable)->alias('a')
            ->where('id', '=', $id)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function updateListByData($condition, $data)
    {
        $condition = $this->assembleFilterCondition($condition);
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function updateListByManyId($arrId, $data)
    {
        $res = Db::table($this->primaryTable)->alias('a')
            ->whereIn('a.id', $arrId)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeRowById($id)
    {
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)
            ->where('id', '=', $id)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeListByManyId($arrId)
    {
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)->alias('a')
            ->whereIn('a.id', $arrId)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeListByData($data)
    {
        $condition = $this->assembleFilterCondition($data);
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function addProjectModuleTrunk($data)
    {
        Db::table($this->primaryTable)->startTrans();
        try{
            $trunkData = array(
                'project_basic_id' => $data['project_basic_id'],
                'module_trunk_name' => $data['module_trunk_name']
            );
            $newTrunkId = $this->createRow($trunkData);
            if($newTrunkId){
                $moduleBranchList = array_filter(explode("\r\n", $data['module_branch_list']));
                if(empty($moduleBranchList)){
                    Db::table($this->primaryTable)->commit();
                    return $newTrunkId;
                }else{
                    $serviceBranch = new ProjectModuleBranchService();
                    $addManyData = array();
                    foreach($moduleBranchList as $branchName){
                        $addManyData[] = array(
                            'module_trunk_id' => $newTrunkId,
                            'module_branch_name' => $branchName
                        );
                    }
                    $res = $serviceBranch->createManyRow($addManyData);
                    if($res){
                        Db::table($this->primaryTable)->commit();
                        return $res;
                    }else{
                        Db::table($this->primaryTable)->rollback();
                        throw new \Exception("add module branch fail");
                    }
                }
            }else{
                Db::table($this->primaryTable)->rollback();
                throw new \Exception("add module trunk fail");
            }
        }catch(\Exception $e){
            Db::table($this->primaryTable)->rollback();
            throw new \Exception($e);
        }
    }

    public function getWholeTree($data = [])
    {
        $moduleTrunkList = $this->getListNoPage($data);
        $serviceModuleBranch = new ProjectModuleBranchService();
        $arrModuleTrunkId = array_column($moduleTrunkList, 'id');
        $condition = array(
            'module_trunk_id' => $arrModuleTrunkId,
        );
        $moduleBranchList = $serviceModuleBranch->getListNoPage($condition);

        $moduleTrunkTree = array();
        foreach($moduleTrunkList as $trunkItem){
            $nodeData = array(
                'trunk_info' => $trunkItem,
                'branch_list' => array()
            );
            foreach($moduleBranchList as $branchItem){
                if($trunkItem['id'] == $branchItem['module_trunk_id']){
                    $nodeData['branch_list'][] = $branchItem;
                }
            }
            $moduleTrunkTree[] = $nodeData;
        }
        return $moduleTrunkTree;
    }
}